package net.chrisrichardson.ec2deployer.core

import org.apache.commons.logging.*;

public class Ssh {

    def Log logger = LogFactory.getLog(getClass())

    def sshOpts = "-o BatchMode=yes -o StrictHostKeyChecking=no"
    private AWSProperties awsProperties

    def Ssh(AWSProperties awsProperties) {
        this.awsProperties = awsProperties
    }


    // todo - somehow check that permissions on id_rsa-gsg-keypair are ok

    public void ssh(String publicDnsName, String command, String input = null, processMonitor = null, String options = "") {
        logger.debug("ssh on ${publicDnsName}:  $command")
        new ProcessExecutor().execute("${awsProperties.sshDir}/ssh $sshOpts -i ${awsProperties.keyPairFile} $options root@$publicDnsName $command", input, processMonitor)
    }

    public void scpUp(String publicDnsName, String fromFile, String toFile) {
        logger.debug("scp to ${publicDnsName}: $fromFile -> $toFile")
        new ProcessExecutor().execute("${awsProperties.sshDir}/scp $sshOpts -i ${awsProperties.keyPairFile} $fromFile root@$publicDnsName:$toFile")
    }

    public void scpDown(String publicDnsName, String fromFile, String toFile) {
        logger.debug("scp from ${publicDnsName}: $fromFile -> $toFile")
        new ProcessExecutor().execute("${awsProperties.sshDir}/scp $sshOpts -i ${awsProperties.keyPairFile} root@$publicDnsName:$fromFile $toFile ")
    }

    def waitUntilSshAvailable(publicDnsName) {
        logger.debug "waiting for ssh: " + publicDnsName
        Socket s = null

        for (int i: 0..10) {
            try {
                s = new Socket(publicDnsName, 22);
                logger.debug "Connected"
                break;
            } catch (IOException e) {
                logger.debug("connection failed:", e)
            } finally {
                try {
                    if (s) s.close();
                } catch (IOException e) {
                }
            }
            Thread.sleep 5 * 1000
        }
    }

}
